package com.cq.hd.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cq.hd.common.enums.ResponseEnums;
import com.cq.hd.common.enums.biz.AgentBindApplyAuditStateEnum;
import com.cq.hd.common.enums.biz.AgentEnterStateEnum;
import com.cq.hd.common.enums.biz.AgentStateEnum;
import com.cq.hd.common.enums.biz.ConfigSettingKeyEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.StringUtils;
import com.cq.hd.member.api.dto.*;
import com.cq.hd.member.api.vo.*;
import com.cq.hd.member.mapper.*;
import com.cq.hd.member.po.*;
import com.cq.hd.member.service.TbAgentBindApplyService;
import com.cq.hd.member.service.TbBusinessGroupService;
import com.cq.hd.member.service.TbConfigSettingService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.cq.hd.common.enums.biz.AgentBindApplyAuditStateEnum.AUDIT_PASS;

/**
 * <p>
 * 经纪人绑定申请记录 服务实现类
 * </p>
 */
@Slf4j
@Service
public class TbAgentBindApplyServiceImpl extends ServiceImpl<TbAgentBindApplyMapper, TbAgentBindApplyPo> implements TbAgentBindApplyService {

    @Autowired
    private TbBusinessMapper businessMapper;

    @Autowired
    private TbAppUserMapper appUserMapper;

    @Autowired
    private TbBusinessGroupMapper businessGroupMapper;

    @Autowired
    private TbBusinessGroupService businessGroupService;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private TbBusinessAgentMapper businessAgentMapper;

    @Autowired
    private TbBusinessAgentBindRecordMapper businessAgentBindRecordMapper;

    @Autowired
    private TbConfigSettingService configSettingService;

    /**
     * 判断是否有审核中，已通过的申请，如果有，不能继续申请
     * 邀请码状态：0-未申请，1-待审核，2-已通过，3-未通过
     */
    private void checkApplyRecord(Long inviterUserId, Long applyUserId, Long businessId, Long agentId, PreAgentApplyVo preAgentApplyVo) {
        // 判断是否已经绑定
        TbBusinessAgentPo businessAgentPo = businessAgentMapper.getBusinessAgentRecord(businessId, agentId, applyUserId);
        if (businessAgentPo != null) {
            preAgentApplyVo.setState(AUDIT_PASS.getValue());
            return;
        }

        AgentBindApplyDto dto = new AgentBindApplyDto();
        dto.setInviterUserId(inviterUserId);
        dto.setApplyUserId(applyUserId);
        TbAgentBindApplyPo po = baseMapper.getByDto(dto);
        if (po != null && Objects.equals(po.getAuditState(), AgentBindApplyAuditStateEnum.AUDIT_PENDING.getValue())) {
            preAgentApplyVo.setState(AgentBindApplyAuditStateEnum.AUDIT_PENDING.getValue());
            return;
        }

        if (po != null && Objects.equals(po.getAuditState(), AgentBindApplyAuditStateEnum.AUDIT_REJECT.getValue())) {
            preAgentApplyVo.setState(AgentBindApplyAuditStateEnum.AUDIT_REJECT.getValue());
            preAgentApplyVo.setApplyReason(po.getApplyReason());
            preAgentApplyVo.setUsername(po.getUsername());
            preAgentApplyVo.setMobile(po.getMobile());
            preAgentApplyVo.setRefuseReason(po.getRefuseReason());
            return;
        }

        preAgentApplyVo.setState(AgentBindApplyAuditStateEnum.AUDIT_NONE.getValue());
    }

    private PreAgentApplyVo subAgentPreApply(PreAgentEnterApplyDto preAgentApplyMerchantDto) {
        PreAgentApplyVo preAgentApplyVo = new PreAgentApplyVo();
        preAgentApplyVo.setAgentLevel(2);

        Long userId = preAgentApplyMerchantDto.getUserId();

        String inviteCode = preAgentApplyMerchantDto.getSettleCode();
        AppUserVo inviter = appUserMapper.getByInviteCode(inviteCode);
        if (inviter == null || inviter.getAgentId() > 0) {
            Throw.isBusinessException("邀请码有误[1]");
        }

        // 不能邀请自己
        if (inviter.getId().equals(userId)) {
            Throw.isBusinessException("不能邀请自己");
        }

        Integer count = businessMapper.selectCount(new QueryWrapper<TbBusinessPo>()
                .eq("del_state", 0)
                .eq("user_id", userId));
        if (count > 0) {
            Throw.isBusinessException("你是商家，不能成为二级经纪人");
        }

        // 受邀请的用户，如果已经是其他人的经纪人，或者是一级经纪人，不能再接受邀请了
        TbAppUserPo user = appUserMapper.selectById(userId);
        if (user == null || user.getDelState() != 0) {
            Throw.isBusinessException(ResponseEnums.USER_NOT_FOUND);
        }
        count = businessAgentMapper.selectCount(new QueryWrapper<TbBusinessAgentPo>()
                .eq("del_state", 0)
                .eq("user_id", userId));
        if (count > 0) {
            Throw.isBusinessException("你已经是经纪人，不能继续成为二级经纪人");
        }

        checkApplyRecord(inviter.getId(), userId, 0L, inviter.getId(), preAgentApplyVo);
        return preAgentApplyVo;
    }

    @Override
    public PreAgentApplyVo preApply(PreAgentEnterApplyDto preAgentApplyMerchantDto) {
        PreAgentApplyVo preAgentApplyVo = new PreAgentApplyVo();

        Long userId = preAgentApplyMerchantDto.getUserId();
        if (userId == null || userId <= 0) {
            Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
        }

        String settleCode = preAgentApplyMerchantDto.getSettleCode();
        if (StringUtils.isBlank(settleCode)) {
            Throw.isBusinessException("邀请码不能为空");
        }

        // 邀请二级经纪人
        if (StringUtils.isUserInviteCode(settleCode)) {
            return subAgentPreApply(preAgentApplyMerchantDto);
        }

        preAgentApplyVo.setAgentLevel(1);
        // 根据邀请码，查询商家数据
        List<TbBusinessPo> businessPos = businessMapper.selectList(new QueryWrapper<TbBusinessPo>()
                .eq("del_state", 0)
                .eq("state", 1)
                .eq("invite_code", settleCode));
        if (CollectionUtils.isEmpty(businessPos)) {
            Throw.isBusinessException("邀请码错误[1]");
        }
        TbBusinessPo businessPo = businessPos.get(0);

        if (businessPo.getUserId().equals(userId)) {
            log.error("受邀用户与商家是同一个用户，userId：{}", userId);
            Throw.isBusinessException("不能成为商家自己的经纪人");
        }

        // 如果是二级经纪人，不能成为一级经纪人
        TbAppUserPo user = appUserMapper.selectById(userId);
        if (user == null || user.getDelState() != 0) {
            Throw.isBusinessException(ResponseEnums.USER_NOT_FOUND);
        }
        if (user.getAgentId() > 0) {
            Throw.isBusinessException("你是二级经纪人，不能成为一级经纪人");
        }

        checkApplyRecord(businessPo.getUserId(), userId, businessPo.getId(), 0L, preAgentApplyVo);
        return preAgentApplyVo;
    }

    /**
     * 经纪人绑定申请
     * @param agentBindApplyDto
     * @return
     */
    @Override
    public AgentBindApplyVo apply(AgentBindApplyDto agentBindApplyDto) {
        String code = agentBindApplyDto.getCode();
        String username = agentBindApplyDto.getUsername();
        String mobile = agentBindApplyDto.getMobile();
        Long applyUserId = agentBindApplyDto.getUserId();

        AgentBindApplyVo agentBindApplyVo = new AgentBindApplyVo();

        if (agentBindApplyDto.getBusinessId() == null) {
            if (applyUserId == null || StringUtils.isBlank(code)) {
                Throw.isBusinessException("邀请链接错误");
            }
        }
        if (username == null || StringUtils.isBlank(username)) {
            Throw.isBusinessException("请输入姓名");
        }
        if (mobile == null || StringUtils.isBlank(mobile)) {
            Throw.isBusinessException("请输入手机号");
        }

        TbAppUserPo tbAppUserPo = appUserMapper.selectById(applyUserId);
        if (tbAppUserPo == null || tbAppUserPo.getDelState() != 0) {
            Throw.isBusinessException("未找到用户数据");
        }

        Long businessId = 0L;
        Long agentId = 0L;
        Long inviterUserId;
        int agentLevel;
        Long groupId = agentBindApplyDto.getGroupId();
        if (StringUtils.isUserInviteCode(code)) {
            AppUserVo inviter = appUserMapper.getByInviteCode(code);
            if (inviter == null || inviter.getAgentId() > 0) {
                Throw.isBusinessException("邀请码有误[2]");
            }
            if (inviter.getId().equals(applyUserId)) {
                Throw.isBusinessException("不能成为自己的经纪人");
            }
            inviterUserId = inviter.getId();
            agentId = inviterUserId;
            agentLevel = 2;

            // 如果没有传分组id，查找该经纪人的默认分组
            if (groupId == null || groupId < 1) {
                TbBusinessGroupPo agentGroupPo = businessGroupService.getDefaultGroupWithInit(businessId, agentId);
                groupId = agentGroupPo.getId();
            } else {
                TbBusinessGroupPo agentGroupPo = businessGroupMapper.getGroupById(groupId);
                if (agentGroupPo == null || !inviterUserId.equals(agentGroupPo.getAgentId())) {
                    Throw.isBusinessException("分组id有误【" + groupId + "】");
                }
            }
        } else {
            TbBusinessPo tbBusinessPo = null;
            // 如果是从商家主页主动申请
            if (agentBindApplyDto.getBusinessId() != null) {
                tbBusinessPo = businessMapper.selectById(agentBindApplyDto.getBusinessId());
            } else {
                // 商家邀请
                tbBusinessPo = businessMapper.getByInviteCode(code);
            }

            if (tbBusinessPo == null) {
                Throw.isBusinessException("邀请码错误[2]");
            }
            if (tbBusinessPo.getUserId().equals(applyUserId)) {
                log.error("受邀用户与商家是同一个用户，applyUserId{}", applyUserId);
                Throw.isBusinessException("不能成为商家自己的经纪人");
            }
            businessId = tbBusinessPo.getId();

            // 如果没有传分组id，查找该商家的默认分组
            if (groupId == null || groupId < 1) {
                TbBusinessGroupPo businessGroupPo = businessGroupMapper.getDefaultGroup(businessId);
                groupId = businessGroupPo.getId();
            } else {
                TbBusinessGroupPo businessGroupPo = businessGroupMapper.getGroupById(groupId);
                if (businessGroupPo == null || !businessId.equals(businessGroupPo.getBusinessId())) {
                    Throw.isBusinessException("分组id有误【" + groupId + "】");
                }
            }

            businessId = tbBusinessPo.getId();
            inviterUserId = tbBusinessPo.getUserId();
            agentLevel = 1;
        }

        // 判断能不能继续申请 1待填写信息 2申请已提交，待审核 3已成功绑定
        PreAgentApplyVo preAgentApplyVo = new PreAgentApplyVo();
        checkApplyRecord(inviterUserId, applyUserId, businessId, agentId, preAgentApplyVo);
        int applyState = preAgentApplyVo.getState();
        if (applyState == AgentBindApplyAuditStateEnum.AUDIT_PENDING.getValue()) {
            Throw.isBusinessException("申请已提交，待审核");
        } else if (applyState == AUDIT_PASS.getValue()) {
            Throw.isBusinessException("你已经绑定成功，请勿重复提交");
        }

        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());

        try {
            // 经纪人绑定申请记录
            TbAgentBindApplyPo tbAgentBindApplyPo = new TbAgentBindApplyPo();
            tbAgentBindApplyPo.setInviterUserId(inviterUserId);
            tbAgentBindApplyPo.setApplyUserId(applyUserId);
            tbAgentBindApplyPo.setAgentLevel(agentLevel);
            tbAgentBindApplyPo.setBusinessId(businessId);
            tbAgentBindApplyPo.setAgentId(agentId);
            tbAgentBindApplyPo.setUsername(username);
            tbAgentBindApplyPo.setMobile(mobile);
            tbAgentBindApplyPo.setGroupId(groupId);
            tbAgentBindApplyPo.setCreateTime(LocalDateTime.now());
            tbAgentBindApplyPo.setApplyReason(agentBindApplyDto.getApplyReason());
            save(tbAgentBindApplyPo);

            // 是否自动审核通过
            boolean checkAutoAudit = checkAutoAudit(tbAgentBindApplyPo);
            String agentBindApplyMessage = getAgentBindApplyMessage(tbAgentBindApplyPo, checkAutoAudit);
            agentBindApplyVo.setMessage(agentBindApplyMessage);
            transactionManager.commit(transaction);
        } catch (Exception e) {
            //回滚事务
            transactionManager.rollback(transaction);
            log.error("<经纪人绑定>事务异常回滚", e);
            Throw.isBusinessException("受邀失败");
        }
        agentBindApplyVo.setAgentLevel(agentLevel);
        return agentBindApplyVo;
    }

    private String getAgentBindApplyMessage(TbAgentBindApplyPo tbAgentBindApplyPo, boolean autoAudit) {
        if (!autoAudit) {
            return "已申请，请耐心等待审核";
        }
        // 一级经纪人
        if (tbAgentBindApplyPo.getAgentLevel() == 1) {
            TbBusinessPo tbBusinessPo = businessMapper.selectById(tbAgentBindApplyPo.getBusinessId());
            return "您已成为" + tbBusinessPo.getBusinessShortName() + "的经纪人";
        } else if (tbAgentBindApplyPo.getAgentLevel() == 2) {
            // 二级经纪人
            TbAppUserPo tbAppUserPo = appUserMapper.selectById(tbAgentBindApplyPo.getAgentId());
            return "您已成为" + tbAppUserPo.getNickName() + "的经纪人";
        }
        return "您已成为经纪人";
    }

    private boolean checkAutoAudit(TbAgentBindApplyPo agentBindApplyPo) {
        Long inviterUserId = agentBindApplyPo.getInviterUserId();
        String agentAutoApproval = configSettingService.getUserConfigValueOfDefault(
                inviterUserId, ConfigSettingKeyEnum.AGENT_AUTO_APPROVAL.name());
        if (StringUtils.isBlank(agentAutoApproval)) {
            return false;
        }
        if (!agentAutoApproval.equals("true")) {
            return false;
        }
        AgentBindApplyAuditDto agentBindApplyAuditDto = new AgentBindApplyAuditDto();
        agentBindApplyAuditDto.setId(agentBindApplyPo.getId());
        agentBindApplyAuditDto.setInviterUserId(agentBindApplyPo.getInviterUserId());
        agentBindApplyAuditDto.setAuditState(AUDIT_PASS.getValue());
        return audit(agentBindApplyAuditDto);
    }

    @Override
    public Integer waitAuditCount(Long inviterUserId) {
        return baseMapper.getWaitAuditCount(inviterUserId);
    }

    @Override
    public Page<AgentBindApplyPageVo> page(AgentBindApplyPageDto agentBindApplyPageDto) {
        PageHelper.startPage(agentBindApplyPageDto.getPageNum(), agentBindApplyPageDto.getPageSize());
        List<AgentBindApplyPageVo> agentBindApplyPageVos = baseMapper.listByDto(agentBindApplyPageDto);
        if (CollectionUtils.isEmpty(agentBindApplyPageVos)) {
            return new Page<>();
        }

        // 申请人id
        List<Long> userIds = agentBindApplyPageVos.stream().map(AgentBindApplyPageVo::getApplyUserId).collect(Collectors.toList());
        Map<Long, TbAppUserPo> appUserMap = new HashMap<>();
        List<TbAppUserPo> appUserPos = appUserMapper.selectList(new QueryWrapper<TbAppUserPo>()
                .in("id", userIds));
        if (!CollectionUtils.isEmpty(appUserPos)) {
            appUserMap = appUserPos.stream()
                    .collect(Collectors.toMap(TbAppUserPo::getId, Function.identity()));
        }

        Map<Long, TbAppUserPo> finalAppUserMap = appUserMap;
        agentBindApplyPageVos.forEach(vo -> {
            TbAppUserPo appUserPo = finalAppUserMap.get(vo.getApplyUserId());
            if (appUserPo != null) {
                vo.setNickName(appUserPo.getNickName());
                vo.setAvatar(appUserPo.getAvatar());
            }
        });

        PageInfo<AgentBindApplyPageVo> pageInfo = new PageInfo<>(agentBindApplyPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    // 我的入驻申请列表
    @Override
    public Page<MyAgentBindApplyPageVo> myApplyPage(MyAgentBindApplyPageDto myAgentBindApplyPageDto) {
        PageHelper.startPage(myAgentBindApplyPageDto.getPageNum(), myAgentBindApplyPageDto.getPageSize());
        List<MyAgentBindApplyPageVo> agentBindApplyPageVos;
        if (myAgentBindApplyPageDto.getAgentLevel() == 1) {
            agentBindApplyPageVos = baseMapper.listMyBusinessApply(myAgentBindApplyPageDto);
        } else {
            agentBindApplyPageVos = baseMapper.listMyAgentApply(myAgentBindApplyPageDto);
        }
        if (CollectionUtils.isEmpty(agentBindApplyPageVos)) {
            return new Page<>();
        }
        PageInfo<MyAgentBindApplyPageVo> pageInfo = new PageInfo<>(agentBindApplyPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    public void checkBusinessMaxInviteAgentCount(Long businessId) {
        TbBusinessPo businessPo = businessMapper.selectById(businessId);
        if (businessPo == null || businessPo.getDelState() != 0) {
            Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
        }

        Integer maxCount = businessPo.getMaxInviteAgentCount();
        // 不限
        if (maxCount == null) {
            return;
        }

        // 商家当前经纪人数量
        Integer count = businessAgentMapper.selectCount(new QueryWrapper<TbBusinessAgentPo>()
                .eq("del_state", 0)
                .eq("business_id", businessId));
        if (count != null && count >= maxCount) {
            Throw.isBusinessException("您的经纪人数量已达上限");
        }
    }

    @Override
    public Boolean audit(AgentBindApplyAuditDto agentBindApplyAuditDto) {
        AgentBindApplyDto dto = new AgentBindApplyDto();
        dto.setId(agentBindApplyAuditDto.getId());
        dto.setInviterUserId(agentBindApplyAuditDto.getInviterUserId());
        TbAgentBindApplyPo po = baseMapper.getByDto(dto);
        if (po == null) {
            Throw.isBusinessException("入驻申请记录不存在");
        }

        if (!Objects.equals(po.getAuditState(), AgentBindApplyAuditStateEnum.AUDIT_PENDING.getValue())) {
            Throw.isBusinessException("该入驻申请已经审核过");
        }

        String refuseReason = agentBindApplyAuditDto.getRefuseReason();
        if (Objects.equals(po.getAuditState(), AgentBindApplyAuditStateEnum.AUDIT_REJECT.getValue())) {
            if (refuseReason == null || refuseReason.isEmpty()) {
                Throw.isBusinessException("请输入审核不通过理由");
            }
        }

        Long userId = po.getApplyUserId();
        TbAppUserPo tbAppUserPo = appUserMapper.selectById(userId);
        if (tbAppUserPo == null || tbAppUserPo.getDelState() != 0) {
            Throw.isBusinessException("未找到用户数据");
        }

        Long businessId = 0L;
        Long agentId = 0L;
        if (po.getAgentLevel() == 1) {
            // 如果用户是别人的二级经纪人，那么不能成为一级经纪人
            if (tbAppUserPo.getAgentState().equals(AgentStateEnum.OPEN.getValue()) && tbAppUserPo.getAgentId() > 0) {
                Throw.isBusinessException("该用户是二级经纪人，不能成为一级经纪人");
            }

            businessId = po.getBusinessId();

            // 判断商家可邀请经纪人数量是否到达上限
            checkBusinessMaxInviteAgentCount(businessId);
        } else {
            int count = businessAgentMapper.selectCount(new QueryWrapper<TbBusinessAgentPo>()
                    .eq("del_state", 0)
                    .eq("user_id", userId));
            if (count > 0) {
                Throw.isBusinessException("该用户已经是经纪人");
            }

            agentId = po.getInviterUserId();
        }

        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());

        LocalDateTime now = LocalDateTime.now();
        try {
            po.setAuditState(agentBindApplyAuditDto.getAuditState());
            po.setRefuseReason(refuseReason);
            po.setAuditTime(now);
            baseMapper.updateById(po);

            // 审核通过，写入绑定关系表
            if (Objects.equals(po.getAuditState(), AUDIT_PASS.getValue())) {
                // 是否已经有对应的绑定记录
                TbBusinessAgentPo businessAgentPo = businessAgentMapper.getBusinessAgentRecord(businessId, agentId, userId);
                if (businessAgentPo != null) {
                    Throw.isBusinessException("该经纪人已有绑定记录，请勿重复绑定");
                }

                TbBusinessAgentPo tbBusinessAgentPo = new TbBusinessAgentPo();
                tbBusinessAgentPo.setUserId(userId);
                tbBusinessAgentPo.setBusinessId(businessId);
                tbBusinessAgentPo.setAgentId(agentId);
                tbBusinessAgentPo.setGroupId(po.getGroupId());
                tbBusinessAgentPo.setTotalOrderCount(0);
                tbBusinessAgentPo.setTotalOrderAmt(BigDecimal.ZERO);
                tbBusinessAgentPo.setTotalCommission(BigDecimal.ZERO);
                tbBusinessAgentPo.setTotalWithdrawalCommission(BigDecimal.ZERO);
                tbBusinessAgentPo.setState(AgentEnterStateEnum.WAIT_ENTER.getValue()); // todo 这个待确认
                tbBusinessAgentPo.setCreateTime(now);
                int insert = businessAgentMapper.insert(tbBusinessAgentPo);
                if (insert == 0) {
                    log.error("[审核经纪人入驻申请]经纪人绑定商家失败,添加经纪人商家关联记录失败,userId:{}, businessId:{}", userId, businessId);
                    Throw.isBusinessException("审核失败");
                }

                // 更新商家经纪人数量
                if (businessId > 0) {
                    businessMapper.updateAgentCount(businessId);
                }

                // todo 更新用户邀请人数

                // 初始化默认分组
                businessGroupService.getDefaultGroupWithInit(businessId, agentId);

                // 添加商家经纪人绑定记录
                TbBusinessAgentBindRecordPo tbBusinessAgentBindRecordPo = new TbBusinessAgentBindRecordPo();
                tbBusinessAgentBindRecordPo.setUserId(userId);
                tbBusinessAgentBindRecordPo.setBusinessId(businessId);
                tbBusinessAgentBindRecordPo.setAgentId(agentId);
                tbBusinessAgentBindRecordPo.setBindTime(now);
                tbBusinessAgentBindRecordPo.setCreateTime(now);
                insert = businessAgentBindRecordMapper.insert(tbBusinessAgentBindRecordPo);
                if (insert <= 0) {
                    Throw.isBusinessException("审核失败");
                }

                // 第一次入驻，设置入驻时间
                if (tbAppUserPo.getEnterTime() == null) {
                    tbAppUserPo.setEnterTime(now);
                }
                // 是否是经纪人(1-不是，2-是)
                tbAppUserPo.setAgentState(AgentStateEnum.OPEN.getValue());
                tbAppUserPo.setAgentId(agentId);
                tbAppUserPo.setUpdateTime(now);
                tbAppUserPo.setAgentLevel(po.getAgentLevel());
                // 如果用户的 realName 为空，把入驻申请的名称填充进去
                if (StringUtils.isBlank(tbAppUserPo.getRealName())) {
                    tbAppUserPo.setRealName(po.getUsername());
                }
                int update = appUserMapper.updateById(tbAppUserPo);
                if (update == 0) {
                    log.error("经纪人入驻申请审核,更新经纪人状态失败,userId:{}, businessId:{}, agentId:{}", userId, businessId, agentId);
                    Throw.isBusinessException("审核失败");
                }
            }

            transactionManager.commit(transaction);
        } catch (Exception e) {
            // 回滚事务
            transactionManager.rollback(transaction);
            log.error("<经纪人入驻申请审核>事务异常回滚", e);
            Throw.isBusinessException("审核失败");
            return false;
        }

        return true;
    }

    @Override
    public TbAgentBindApplyPo getLatestBusinessAgentApply(Long businessId, Long applyUserId) {
        LambdaQueryWrapper<TbAgentBindApplyPo> last = Wrappers.<TbAgentBindApplyPo>lambdaQuery()
                .eq(TbAgentBindApplyPo::getBusinessId, businessId)
                .eq(TbAgentBindApplyPo::getApplyUserId, applyUserId)
                .orderByDesc(TbAgentBindApplyPo::getId)
                .last("limit 1");
        return baseMapper.selectOne(last);
    }
}
